<template>

	<view class="content">
		<view class="content-video">
			<video id="myVideo" :src="vedioUrl" @timeupdate="handleTimeUpdate" :initial-time="historyTime" controls
				autoplay :object-fit="objectFit" enable-progress-gesture="true" @error="videoErrorCallback"
				page-gesture="true" vslide-gesture-in-fullscreen :title="vedioTitle" :danmu-list="danmuList"
				enable-danmu danmu-btn></video>
		</view>

		<text class="video-name">
			{{ videoName }}
		</text>

		<!-- 详情 -->
		<view class="video-detial" @click="showVideoDetial"> {{ getDetialText() }}
			<template v-if="videoDetial">
				<view>

					<view class="type-info">
						<!-- test 为 true 时显示 -->
						<view class="type-info-title">
							分类：
						</view>
						<view class="type-info-name" @click="checkByType(mediaTypeInfo.id)">
							<text>{{ mediaTypeInfo.typeName }}</text>
						</view>
					</view>

					<view class="tag-info">
						<view class="tag-info-title">
							标签：
						</view>
						<view class="tag-info-name">
							<view v-for="(item, index) in adTagVOList" :key="item.id">
								<text @click="checkByTag(item.id)">{{ item.tagName + getSeparator(index) }}</text>
							</view>
						</view>
					</view>

				</view>
			</template>
			<template v-else>
				<view> </view>
			</template>
		</view>

		<view class="content-dm">
			<view class="input-item">
				<input class="input" v-model="danmuValue" type="text" @confirm="sendDanmu" placeholder="在此处输入弹幕内容" />
			</view>
			<view class="uni-btn-v">
				<button @click="sendDanmu" class="page-body-button">发送</button>
			</view>
		</view>

		<!-- 视频 -->
		<view class="viedo_list">
			<view class="vedio_item" v-for="item in videoData" :key="item.id">
				<image :src="item.videoCover" mode="scaleToFill" @click="gotToVideoDetial(item.id)" />
				<view class="name">
					<text class="vedio_name" @click="gotToVideoDetial(item.id)">{{ item.videoName }}</text>
				</view>
			</view>

		</view>

	</view>

</template>

<script>
import { findDetial, findDanmaku, saveDanmaku, saveOrUpdateHistory, findVideoDetailList } from '@/api/media/media'

export default {
	data() {
		return {
			vedioUrl: undefined,
			vedioTitle: '',
			objectFit: 'contain',
			videoName: undefined,
			// 通用详情/删除条件
			commonForm: {
				id: undefined,
				idList: [],
				tableName: 'ad_user_organization'
			},

			danmuList: [],

			sendDanmuData: {
				videoId: undefined,
				moment: undefined,
				danmakuContent: undefined,
				danmakuColor: undefined
			},

			danmuValue: '',
			// 初始时间 历史记录时间
			historyTime: undefined,
			// 当前播放时间
			currentTime: undefined,
			vedioCondition: {
				id: undefined,
				videoId: undefined
			},

			// 播放记录信息
			playHistory: {
				videoId: undefined,
				playMoment: undefined,
				videoName: undefined
			},

			videoData: undefined,
			videoDetial: false,

			detialText: '详情',
			mediaTypeInfo: undefined,
			adTagVOList: undefined,
			// 弹幕颜色取值范围
			colorArr: ['#8a5ef7', '#256bf2', '#aa35b9', '#6c292d', '#ac5450', '#ec3e85', '#663ced', '#ec468e', '#a828ce', '#08a998']
		}
	},

	onLoad: function (option) {
		// console.log(option.id); //打印出上个页面传递的参数。		
		this.vedioCondition.id = option.id
		this.handleFindDetial()
		this.handleFindDanmaku()
		this.handlefindVideoDetailList()
	},

	created() {

	},

	onReady: function (res) {
		// #ifndef MP-ALIPAY
		this.videoContext = uni.createVideoContext('myVideo')
		// #endif 
	},

	destroyed() {
		this.handSaveOrUpdateHistory()
	},

	methods: {
		// 获取分隔符
		getSeparator(index) {
			// 最后一个元素 返回空字符串 否则返回占位符 ,
			return index == this.adTagVOList.length - 1 ? '' : ','
		},

		// 分类跳转
		checkByType(typeId) {
			this.pausePlay()
			console.log('进入分类', typeId);
			// 进入分类
			uni.navigateTo({
				url: '/pages/media/media?typeId=' + typeId
			});
		},

		// 标签跳转
		checkByTag(tagId) {
			this.pausePlay()
			console.log('进入标签', tagId);
			// 进入标签
			uni.navigateTo({
				url: '/pages/media/media?tagetId=' + tagId
			});
		},

		// 显示详情
		showVideoDetial() {
			console.log('触发详情操作');
			this.videoDetial = !this.videoDetial
		},

		// 获取详情标题
		getDetialText() {
			return this.videoDetial ? this.detialText + ':' : '>' + this.detialText
		},

		// 播放进度变化时触发
		handleTimeUpdate(e) {
			this.currentTime = e.detail.currentTime; // 获取当前播放时间
			// console.log('当前播放时间:', this.currentTime);
		},

		// 保存或更新视频播放记录
		handSaveOrUpdateHistory() {
			console.log('保存历史记录 当前播放时间', this.currentTime);

			this.playHistory.playMoment = this.currentTime
			this.playHistory.videoId = this.vedioCondition.id
			saveOrUpdateHistory(this.playHistory)
		},

		// 发送弹幕
		sendDanmu: function () {
			// const randomColor = this.getRandomColor()
			// 获取数组的长度
			const length = this.colorArr.length
			// 生成一个随机索引
			const randomIndex = Math.floor(Math.random() * length);
			// 获取随机值
			const randomColor = this.colorArr[randomIndex];

			this.videoContext.sendDanmu({
				text: this.danmuValue,
				color: randomColor
			});

			// 封装保存值
			this.sendDanmuData.videoId = this.vedioCondition.id
			this.sendDanmuData.moment = this.currentTime
			this.sendDanmuData.danmakuContent = this.danmuValue
			this.sendDanmuData.danmakuColor = randomColor

			this.handelSaveDanmaku()
			this.danmuValue = '';
		},

		videoErrorCallback: function (e) {
			// uni.showModal({
			// 	content: e.target.errMsg,
			// 	showCancel: false
			// })
		},

		// 查询弹幕
		handleFindDanmaku() {
			this.vedioCondition.videoId = this.vedioCondition.id
			findDanmaku(this.vedioCondition).then(res => {
				const dataArr = res.data
				dataArr.forEach(element => {
					this.danmuList.push({
						text: element.danmakuContent,
						color: element.danmakuColor,
						time: element.moment
					})
				});

				// console.log('弹幕处理结果 --------', JSON.stringify(this.danmuList));
			})
		},

		// 获取播放页视频列表
		handlefindVideoDetailList() {
			this.vedioCondition.videoId = this.vedioCondition.id
			findVideoDetailList(this.vedioCondition).then(res => {
				// console.log(res);
				this.videoData = res.data
			})
		},

		// 获取随机颜色
		getRandomColor: function () {
			const rgb = []
			for (let i = 0; i < 3; ++i) {
				let color = Math.floor(Math.random() * 256).toString(16)
				color = color.length == 1 ? '0' + color : color
				rgb.push(color)
			}
			return '#' + rgb.join('')
		},

		// 查询视频信息
		handleFindDetial() {
			findDetial(this.vedioCondition).then(res => {
				// 处理成基础路径 + 编码加密路径 打包后可正常渲染视频文件
				const dealUrl = res.data.physicalBasePath + encodeURIComponent(res.data.physicalName)
				this.vedioUrl = console.log('处理过后的url路径', dealUrl)

				this.vedioUrl = dealUrl
				this.videoName = res.data.videoName
				this.historyTime = res.data.playMoment
				this.vedioTitle = res.data.videoName
				this.mediaTypeInfo = res.data.adMediaTypeVO
				this.adTagVOList = res.data.adTagVOList
				this.setNavigationBarTitle(res.data.videoName)
			})
		},

		// 保存弹幕
		handelSaveDanmaku() {
			saveDanmaku(this.sendDanmuData).then(res => {
				console.log('保存弹幕', res);
			})
		},

		gotToVideoDetial(id) {
			this.pausePlay()

			uni.navigateTo({
				url: '/pages/video/video?id=' + id
			});
		},

		// 暂停播放
		pausePlay() {
			console.log('暂停当前视频播放');
			this.videoContext.pause();
			console.log('保存播放记录');
			this.handSaveOrUpdateHistory()
		},

		// 设置当前页面的导航栏标题
		setNavigationBarTitle(playTitle) {
			console.log('设置标题', playTitle);

			uni.setNavigationBarTitle({
				title: playTitle
			});
		}
	}
}
</script>

<style lang="scss">
.content {
	display: flex;
	flex-direction: column;
	justify-content: center;
	background-color: #fff;

	.video-name {
		margin-left: 10px;
	}

	.video-detial {
		margin-left: 15px;
		width: 100%;

		.type-info {
			display: flex;

			.type-info-title {
				// background-color: aqua;
				width: 45px;
			}

		}

		.tag-info {
			margin-top: 4px;
			display: flex;
			// flex-direction: row;
			// justify-content: flex-start;

			.tag-info-title {
				display: flex;
				justify-content: flex-start;

				width: 45px;
				margin-right: 0px;
				// background-color: aqua;
			}

			.tag-info-name {
				width: 80%;
				margin-left: 0px;
				display: flex;
				/* 子元素横向排列 */
				flex-direction: row;
				justify-content: flex-start;
				/* 允许子元素换行 */
				flex-wrap: wrap;

				// background-color: red;
				text {
					margin-right: 5px;
				}
			}

		}
	}

	.content-video {
		width: 100%;
		align-items: center;
		// background-color: aqua;

		video {
			width: 100%;
			/* height: auto; */
		}
	}

	.content-dm {
		display: flex;
		width: 100%;
		margin: 10px;
		justify-content: space-between;

		.input-item {
			width: 80%;
			background-color: #f5f6f7;
			height: 45px;
			border-radius: 10px;
			margin-left: 5px;
			margin-right: 5px;

			.input {
				width: 100%;
				font-size: 15px;
				line-height: 20px;
				text-align: left;
				padding-left: 15px;
				margin-top: 10px;
			}
		}

		.uni-btn-v {
			width: 20%;
			margin-right: 35rpx;
			margin-left: 10rpx;

			.page-body-button {
				width: 100%;
				height: 100%;
			}
		}
	}

	.viedo_list {
		background-color: #eee;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;

		.vedio_item {
			width: 355rpx;
			margin: 5px;
			// text-align: center;

			image {
				width: 100%;
				height: 120px;
			}

			.vedio_name {
				text-align: left;
			}
		}
	}
}
</style>